package com.doudou.oauth.service;

import com.doudou.client.BasicClient;
import com.doudou.client.entity.AppClientDetailsDto;
import com.doudou.commons.entity.Result;
import com.doudou.commons.utils.ClientResultUtils;
import com.doudou.commons.utils.ListUtils;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * client的信息自己从数据库中查询
 */
@Component
public final class MyClientDetailsService implements ClientDetailsService {

    @Autowired
    private BasicClient basicClient;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {

        Result<AppClientDetailsDto> client = basicClient.findByClientId(clientId);
        AppClientDetailsDto appClientDetailsDto = ClientResultUtils.getResultIfErrorException(client,"查询client失败");
        if(appClientDetailsDto == null){
            throw new ClientRegistrationException("客户端不存在");
        }
        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setClientId(appClientDetailsDto.getClientId());
        Set<String> redirectUrl = Sets.newHashSet(ListUtils.listString(appClientDetailsDto.getWebServerRedirectUri()));
        baseClientDetails.setRegisteredRedirectUri(redirectUrl);
        baseClientDetails.setAutoApproveScopes(ListUtils.listString(appClientDetailsDto.getAutoapprove()));
        baseClientDetails.setRefreshTokenValiditySeconds(appClientDetailsDto.getRefreshTokenValidity());
        baseClientDetails.setAccessTokenValiditySeconds(appClientDetailsDto.getAccessTokenValidity());
        baseClientDetails.setAuthorizedGrantTypes(ListUtils.listString(appClientDetailsDto.getAuthorizedGrantTypes()));
        baseClientDetails.setClientSecret(appClientDetailsDto.getClientSecret());
//        baseClientDetails.setAdditionalInformation(null);
        baseClientDetails.setAuthorities(Arrays.asList("ROLE_CORP").stream()
                .map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toList()));
        baseClientDetails.setResourceIds(ListUtils.listString(appClientDetailsDto.getResourceIds()));
        baseClientDetails.setScope(ListUtils.listString(appClientDetailsDto.getScope()));
        return baseClientDetails;
    }
}